<template>
    <!-- 头部 -->
    <el-header class="flex items-center justify-between">
        <el-radio-group v-model="isCollapse">
            <el-radio-button :value="false" v-if="isCollapse"><el-icon>
                    <Expand />
                </el-icon></el-radio-button>
            <el-radio-button :value="true" v-if="!isCollapse">
                <el-icon>
                    <Fold />
                </el-icon>
            </el-radio-button>
        </el-radio-group>
        <div class="flex items-center justify-between flex-1 pl-10 pr-2">
            <div class="flex items-center text-sm">
                <el-icon :size="18" class="mr-1 ">
                    <Timer />
                </el-icon>
                {{ currentTime }}
            </div>
            <el-dropdown trigger="click">
                <div class="flex items-center">
                    <el-avatar size="small" :icon="UserFilled" />
                    <span class="ml-1 font-semibold">{{ userInfo.$state.loginname }}</span>
                    <el-icon class="el-icon--right">
                        <ArrowDown />
                    </el-icon>
                </div>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item @click="dialogVisible = true"><el-icon class="mr-1" size="16">
                                <Lock />
                            </el-icon>修改密码</el-dropdown-item>
                        <el-dropdown-item @click="faceVisible = true"><el-icon class="mr-1" size="16">
                                <Camera />
                            </el-icon>人脸注册</el-dropdown-item>
                        <el-dropdown-item divided @click="logout"><el-icon class="mr-1" size="16">
                                <SwitchButton />
                            </el-icon>退出登陆</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>
    </el-header>
    <el-dialog v-model="dialogVisible" title="修改密码" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
            label-width="auto" class="demo-ruleForm">
            <el-form-item label="旧密码" prop="oldpass">
                <el-input v-model="ruleForm.oldpass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="新密码" prop="newpass">
                <el-input v-model="ruleForm.newpass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="确定密码" prop="checkPass">
                <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="editPassword(ruleFormRef)">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="faceVisible" title="人脸识别" width="500">
        <video ref="video" autoplay></video>
        <canvas ref="canvas" style="display:none;"></canvas>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="faceVisible = false">Cancel</el-button>
                <el-button type="primary" @click="faceRegister">
                    Confirm
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup>
import { onBeforeMount, ref, reactive, watch } from 'vue'
import {
    Fold,
    Expand,
    UserFilled,
    ArrowDown,
    Timer,
    Lock,
    Camera,
    SwitchButton
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useInfoStore } from '../../stores/useInfoStore';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ApiPost, ApiPut } from '@/utils/Axios';
const currentTime = ref("")
const router = useRouter()
const userInfo = useInfoStore()
const dialogVisible = ref(false)
const faceVisible = ref(false)
const ruleFormRef = ref<FormInstance>()
const isCollapse = defineModel({ required: true, type: Boolean, default: false })
const video = ref(null);
const canvas = ref(null);
const faceReisterResult = ref(false)

onBeforeMount(() => {
    setInterval(() => {
        currentTime.value = new Date().toLocaleString('zh-CN', { hour12: false, weekday: "long", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" })
    }, 1000)
})

watch(faceVisible, (newVal, oldVal) => {
    if (newVal) {
        navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
                video.value.srcObject = stream;
                video.value.play();
            })
            .catch(error => {
                console.error('Error accessing video stream', error);
            });
    } else {
        if (video.value.srcObject) {
            const stream = video.value.srcObject;
            const tracks = stream.getTracks();
            tracks.forEach(track => {
                track.stop();
            });
            video.value.srcObject = null;
        }
    }
})

const logout = () => {
    window.localStorage.removeItem("token")
    router.push({ path: '/login' })
}

const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入新密码'))
    } else {
        if (ruleForm.checkPass !== '') {
            if (!ruleFormRef.value) return
            ruleFormRef.value.validateField('checkPass')
        }
        callback()
    }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== ruleForm.newpass) {
        callback(new Error("两次密码不一致！"))
    } else {
        callback()
    }
}

const validatePass3 = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入旧密码'))
    } else {
        if (ruleForm.checkPass !== '') {
            if (!ruleFormRef.value) return
            ruleFormRef.value.validateField('checkPass')
        }
        callback()
    }
}

const ruleForm = reactive({
    oldpass: '',
    newpass: '',
    checkPass: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
    newpass: [{ validator: validatePass, trigger: 'blur' }],
    checkPass: [{ validator: validatePass2, trigger: 'blur' }],
    oldpass: [{ validator: validatePass3, trigger: 'blur' }],
})

const editPassword = (formEl: FormInstance | undefined) => {
    console.log(ruleForm)
    formEl.validate((valid) => {
        if (valid) {
            ApiPut("/updatepwd/updatePassword", {
                id: userInfo.$state.id,
                currentPassword: ruleForm.oldpass,
                newPassword: ruleForm.newpass,
            }).then((res) => {
                console.log(res, "123")
                if (res.code === 200) {
                    dialogVisible.value = false
                    ElMessage({
                        message: '修改成功，请重新登陆',
                        type: 'success',
                        duration: 2000,
                        onClose: () => {
                            logout()
                        }
                    })
                } else {
                    ElMessage.error(res.msg)
                }
            })
        }
    })
}

const sendImageData = (imageData) => {
    // 这里使用fetch API发送数据到后端
    // 假设后端服务的URL是 http://your-backend.com/face-recognize
    ApiPost("/facekeyInf/faceReg", {
        id: userInfo.$state.id,
        file: imageData,
    }).then((res) => {
        console.log(res, "人脸注册")
        faceReisterResult.value = true
        if (res.code === 200) {
            faceVisible.value = false
            ElMessage({
                message: '注册成功',
                type: 'success',
                duration: 2000,
            })
        } else {
            ElMessage.error(res.msg)
        }
    })
}

const faceRegister = () => {
    faceReisterResult.value = false
    if (!faceReisterResult.value) {
        canvas.value.width = video.value.videoWidth;
        canvas.value.height = video.value.videoHeight;
        const ctx = canvas.value.getContext('2d');
        ctx.drawImage(video.value, 0, 0, canvas.value.width, canvas.value.height);
        const imageData = canvas.value.toDataURL('image/jpeg');
        sendImageData(imageData)
    }

}
</script>

<style></style>